package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-mgr/cache"
	"red-book-mgr/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")

	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	redBook := models.RedBook{
		Title:   title,
		Content: content,
		Author:  author,
	}

	err := models.DB.Create(&redBook).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "red_id_" + strconv.Itoa(int(redBook.ID))
	models.DB.Where("id=?", redBook.ID).First(&redBook).Debug()   //查询数据
	jsonRedBook, _ := json.Marshal(redBook)                       //转化为json格式
	cache.Rdb.Set(cache.Ctx, redis_key, jsonRedBook, time.Hour*2) //保存到redis中
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var redBook models.RedBook
	redis_key := "user_detail" + id
	cacheRedBook, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if cacheRedBook == "" {
		//从mysql里面读取数据
		models.DB.Where("id=?", id).First(&redBook)
		//转化成json格式
		jsonRedBook, _ := json.Marshal(redBook)
		//保存到redis里
		cache.Rdb.Set(cache.Ctx, redis_key, jsonRedBook, time.Hour*2)
	} else {
		//反序列化(反转成原来的)
		json.Unmarshal([]byte(cacheRedBook), &redBook)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": redBook,
	})
	return

}

func Del(c *gin.Context) {
	id := c.Query("id")
	models.DB.Where("id=?", id).Debug().Delete(&models.RedBook{})

	//删除缓存
	redis_key := "red_id_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 500,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	var redBook []models.RedBook

	redis_key := "redBook_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		//查询
		models.DB.Find(&redBook)
		//转化为json格式
		jsonData, _ := json.Marshal(&redBook)
		//保存到redis里面
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		//返回值
		json.Unmarshal([]byte(cacheData), &redBook)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": redBook,
	})
	return

}
